import java.util.List;
import java.util.Scanner;

public class CommandPatternModule {
    //aaa
    private final Scanner scanner = new Scanner(System.in);
    private final FactoryPatternModule factoryModule;

    public CommandPatternModule(FactoryPatternModule factoryModule) {
        this.factoryModule = factoryModule;
    }

    public void execute() {
        List<AgriculturalMachine> machines = factoryModule.getMachines();
        if (machines.isEmpty()) {
            System.out.println("没有可用的农机设备");
            return;
        }

        while (true) {
            System.out.println("\n===== 任务执行与控制 =====");
            System.out.println("1. 执行任务");
            System.out.println("2. 紧急停止");
            System.out.println("3. 返回主菜单");
            System.out.print("请选择操作(1-3): ");

            int choice = scanner.nextInt();
            scanner.nextLine();  // 消耗换行符

            if (choice == 3) return;

            // 显示农机状态
            System.out.println("\n=== 可用农机 ===");
            for (int i = 0; i < machines.size(); i++) {
                System.out.println((i+1) + ". " + machines.get(i).getStatus());
            }

            System.out.print("选择农机编号: ");
            int index = scanner.nextInt() - 1;
            scanner.nextLine();  // 消耗换行符

            if (index < 0 || index >= machines.size()) {
                System.out.println("无效的农机编号");
                continue;
            }

            AgriculturalMachine machine = machines.get(index);
            TaskInvoker invoker = new TaskInvoker();

            switch (choice) {
                case 1 -> {
                    invoker.setCommand(new StartTaskCommand(machine));
                    invoker.executeCommand();
                }
                case 2 -> {
                    invoker.setCommand(new EmergencyStopCommand(machine));
                    invoker.executeCommand();
                }
                default -> System.out.println("无效选择");
            }
        }
    }
}